#!/usr/bin/env python
# encoding:utf-8
# @Time   : 2019/11/15
# @Author : 胡茂海
# @Site   :
# @File   : import_log.py

import os
import logging
import pathlib
import sys

curpath = pathlib.Path(os.path.abspath(__file__)).parent.parent
sys.path.append(str(curpath / 'etc'))
from SetEnv4Load import syslogdir
import time


class KgemLogger():
    '''
    需要先调用set_logger_file设置好日志文件后才能使用
    '''

    def __init__(self):
        self.__logger = logging.getLogger()
        self.__logger.setLevel(level=logging.INFO)
        self.__file_path_setted = False

    def get_logger(self):
        assert self.__file_path_setted
        return self.__logger

    def set_logger_file(self, logger_file):
        log_dir = str(pathlib.Path(os.path.abspath(logger_file)).parent)
        if not os.path.exists(log_dir):
            os.mkdir(log_dir)
        handler = logging.FileHandler(logger_file, encoding='utf-8')
        handler.setLevel(logging.INFO)
        formatter = logging.Formatter(
            '%(asctime)s - %(process)d[%(thread)d] - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
        handler.setFormatter(formatter)
        self.__logger.addHandler(handler)
        self.__file_path_setted = True


def get_log_file_path(file_name, workday):
    log_name = file_name.split('.')[0] + '.log'
    return os.path.join(pathlib.Path(syslogdir), workday, log_name)


def flog(file_name, date=''):
    file_name = os.path.basename(file_name)
    if date == '':
        date = time.strftime("%Y%m%d", time.localtime(time.time()))
    logobj = KgemLogger()
    logobj.set_logger_file(get_log_file_path(file_name, date))
    logger = logobj.get_logger()
    return logger


# logger = get_file_logger('201701',__file__)


if __name__ == '__main__':
    log = flog(__file__)
    log.info("测试1")
    log.error("测试2")
